package com.zx.Ding.controller;/**
 * Author:JasonZ
 * Data:2023/2/4
 */

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zx.Ding.common.R;
import com.zx.Ding.entity.User;
import com.zx.Ding.service.UserService;
import com.zx.Ding.utils.SMSUtils;
import com.zx.Ding.utils.Sample;
import com.zx.Ding.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @program: Ding
 *
 * @description:
 *
 * @author: JasonZ
 *
 * @create: 2023-02-04 16:45
 **/

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpServletRequest request) throws Exception {
        //获取手机号
        String phone=user.getPhone();
        //生成随机的4位验证码
        if (StringUtils.isNotEmpty(phone)){
            String code = ValidateCodeUtils.generateValidateCode(6).toString();
            log.info("code={}",code);
            //调用阿里云的api发送短信
            SMSUtils.sendMessage("阿丁外卖","SMS_269060329",phone,code);

            /*//需要将生成的验证码保存到session
            request.getSession().setAttribute("code",code);*/

            //将生成的验证码保存到session当中 并且设置有效期为5分钟
            redisTemplate.opsForValue().set("code",code,5, TimeUnit.MINUTES);

            return R.success("手机验证码发送成功");
        }
        return R.error("发送失败");
    }

    /**
     * 登录
     * @param user
     * @return
     */
    @PostMapping("/login")
    public R<User> login(@RequestBody Map user,HttpServletRequest request){
        log.info(user.toString());
        //获取手机号
        String phone=user.get("phone").toString();
        //获取验证码或密码
        String code=user.get("code").toString();
        //从session中获取保存的验证码
      /*  String correctCode = String.valueOf(request.getSession().getAttribute("code"));*/
        //1.从redis当中取出验证码
        String correctCode = (String) redisTemplate.opsForValue().get("code");
        System.out.println("----redis"+correctCode);
        //查询出登录了的用户信息
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getPhone,phone);
        User loginUser = userService.getOne(queryWrapper);

        //进行验证码的比对,说明登录成功
        if (code.equals(correctCode)){
            //登陆成功
            //如果是新手机号 就注册用户
            if (loginUser==null){
                //注册用户
                User NewUser=new User(phone,1,"123");
                //将新用户保存到数据库当中
                userService.save(NewUser);
                //重查登录
                User NewLoginUser = userService.getOne(queryWrapper);
                return R.success(NewLoginUser);
            }
            request.getSession().setAttribute("user",loginUser.getId());
            //登录成功，删除redis当中的验证码
            redisTemplate.delete(phone);
            return R.success(loginUser);
        }
        //如果是已经注册的用户可以使用密码登录
        else  {
            if(loginUser.getPassword().equals(code)){
                request.getSession().setAttribute("user",loginUser.getId());
                return R.success(loginUser);
            }
        }

        return R.error("登陆失败");
    }

    @PostMapping("/register")
    public R<String>register(@RequestBody Map user,HttpServletRequest request){
        return R.success("注册成功");
    }

    @PostMapping("/loginout")
    public R<String>loginout(){
        return R.success("登出成功");
    }
}